import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Dimensions,
  Modal as RNModal,
  TouchableWithoutFeedback,
  Platform,
  SafeAreaView,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import { Avatar } from "@rneui/themed";
import {
  GroupMember,
  GroupMembersListMode,
  ViewAllMembersModalProps,
  GroupMemberRole,
} from "@/types/group-chat";
import GroupMembersList from "../components/MemberList";

// 获取屏幕尺寸
const { width, height } = Dimensions.get("window");

const ViewAllMembersModal: React.FC<ViewAllMembersModalProps> = ({
  visible,
  onClose,
  groupId = "",
  groupName = "",
  groupAvatar = "",
  members = [],
  isAdmin = false,
  isOwner = false,
}) => {
  const { colors } = useTheme();
  const [loading, setLoading] = useState(false);
  const [membersWithRoles, setMembersWithRoles] = useState<GroupMember[]>([]);

  // 获取成员ID列表
  const memberIds = members.map((member) => member.id);

  // 处理成员数据，添加角色信息
  useEffect(() => {
    // 假设第一个成员是群主，第二个是管理员，其余都是普通成员
    // 实际应用中应从API或props获取角色信息
    const processedMembers = members.map((member, index) => {
      let role: GroupMemberRole = GroupMemberRole.MEMBER;

      if (index === 0) {
        role = GroupMemberRole.OWNER;
      } else if (index === 1) {
        role = GroupMemberRole.ADMIN;
      }

      return {
        ...member,
        role,
      };
    });

    setMembersWithRoles(processedMembers);
  }, [members]);

  // 自定义模态框样式
  const styles = StyleSheet.create({
    modalContainer: {
      flex: 1,
      width: "100%",
      height: "100%",
      backgroundColor: "rgba(0, 0, 0, 0.5)",
    },
    modalContent: {
      position: "absolute",
      bottom: 0,
      left: 0,
      right: 0,
      backgroundColor: colors.background,
      borderTopLeftRadius: 16,
      borderTopRightRadius: 16,
      paddingBottom: Platform.OS === "ios" ? 34 : 20,
      maxHeight: height * 0.9,
      minHeight: height * 0.5, // 确保最小高度
    },
    backdrop: {
      flex: 1,
      width: "100%",
    },
    header: {
      flexDirection: "row",
      alignItems: "center",
      justifyContent: "space-between",
      paddingHorizontal: 16,
      paddingVertical: 16,
      borderBottomWidth: 0.5,
      borderBottomColor: colors.border.divider,
    },
    closeButton: {
      padding: 4,
    },
    title: {
      fontSize: 18,
      fontWeight: "600",
      flex: 1,
      textAlign: "center",
    },
    groupInfo: {
      flexDirection: "row",
      alignItems: "center",
      padding: 16,
      borderBottomWidth: 0.5,
      borderBottomColor: colors.border.divider,
    },
    groupAvatar: {
      backgroundColor: "#E1E1E1",
    },
    groupTextInfo: {
      marginLeft: 16,
      flex: 1,
    },
    groupName: {
      fontSize: 18,
      fontWeight: "600",
      marginBottom: 4,
    },
    groupMemberCount: {
      fontSize: 14,
    },
    listContainer: {
      flex: 1,
      height: height * 0.6, // 明确设置高度
    },
  });

  return (
    <RNModal
      visible={visible}
      transparent={true}
      animationType="slide"
      onRequestClose={onClose}
      statusBarTranslucent={true}
    >
      <SafeAreaView style={styles.modalContainer}>
        <TouchableWithoutFeedback onPress={onClose}>
          <View style={styles.backdrop} />
        </TouchableWithoutFeedback>

        <View style={styles.modalContent}>
          {/* 标题栏 */}
          <View style={styles.header}>
            <TouchableOpacity onPress={onClose} style={styles.closeButton}>
              <Ionicons name="close" size={24} color={colors.text.primary} />
            </TouchableOpacity>
            <Text style={[styles.title, { color: colors.text.primary }]}>
              群聊成员
            </Text>
            <View style={{ width: 32 }} /> {/* 占位，保持标题居中 */}
          </View>

          {/* 群聊信息 */}
          {groupName && (
            <View style={styles.groupInfo}>
              <Avatar
                rounded
                size={50}
                source={{
                  uri:
                    groupAvatar ||
                    "https://randomuser.me/api/portraits/men/32.jpg",
                }}
                containerStyle={styles.groupAvatar}
              />

              <View style={styles.groupTextInfo}>
                <Text
                  style={[styles.groupName, { color: colors.text.primary }]}
                >
                  {groupName}
                </Text>

                <Text
                  style={[
                    styles.groupMemberCount,
                    { color: colors.text.secondary },
                  ]}
                >
                  {members.length}名群成员
                </Text>
              </View>
            </View>
          )}

          {/* 成员列表 */}
          <View style={styles.listContainer}>
            <GroupMembersList
              mode={GroupMembersListMode.INVITE} // 使用INVITE模式但不允许选择
              friends={membersWithRoles}
              loading={loading}
              selectedIds={[]}
              onSelectItem={() => {}} // 空函数，不允许选择
              groupMembers={memberIds} // 所有成员都是群成员
              isAdmin={false} // 不显示操作按钮
              isOwner={false}
            />
          </View>
        </View>
      </SafeAreaView>
    </RNModal>
  );
};

export default ViewAllMembersModal;
